package com.dly.blog.service;

import com.dly.blog.msg.R;
import com.dly.blog.provider.user.TokenProvider;
import com.dly.blog.utile.JsonUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@RequiredArgsConstructor
public class LogoutService implements LogoutHandler {

  private final TokenProvider tokenProvider;

  /**
   * 退出登入 销毁token
   * @param request the HTTP request
   * @param response the HTTP response
   * @param authentication the current principal details
   */
  @SneakyThrows
  @Override
  public void logout(
      HttpServletRequest request,
      HttpServletResponse response,
      Authentication authentication
  ) {
    final String authHeader = request.getHeader("Authorization");
    final String jwt;
    if (authHeader == null ||!authHeader.startsWith("Bearer ")) {
      return;
    }
    jwt = authHeader.substring(7);
    var storedToken = tokenProvider.selectByToken(jwt);
    if (storedToken != null) {
      tokenProvider.updateBathValid(storedToken.getUserId());
      SecurityContextHolder.clearContext();
    }

    response.setStatus(200);
    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");
    response.getWriter().write(Objects.requireNonNull(JsonUtils.writeToJson(R.ok())));
  }
}